﻿namespace DeviceCommons.DeviceMessages.Models.V1
{
    public class DeviceMessage : IDeviceMessage
    {
        public IDeviceMessageHeader? Header { get; set; } = new DeviceMessageHeader();

        public IDeviceMessageInfo? MainDevice { get; set; } = new DeviceMessageInfo();

        public IDeviceMessageChild? ChildDevice { get; set; } = new DeviceMessageChild();

        public int DataLength => (Header?.DataLength ?? 0) + (MainDevice?.DataLength ?? 0) + (ChildDevice?.DataLength ?? 0);

        public void Dispose()
        {
            DisposeMainDevice();
            DisposeChildDevices();
            GC.SuppressFinalize(this);
        }

        private void DisposeMainDevice()
        {
            if (MainDevice?.Reading?.ReadingArray == null) return;
            foreach (var reading in MainDevice.Reading.ReadingArray) DisposeReadingReadings(MainDevice);
        }

        private void DisposeChildDevices()
        {
            if (ChildDevice?.ChildArray == null) return;
            foreach (var child in ChildDevice.ChildArray) DisposeReadingReadings(child);
        }
        private static void DisposeReadingReadings(IDeviceMessageInfo? info)
        {
            if (info?.Reading?.ReadingArray == null) return;
            foreach (var reading in info.Reading.ReadingArray) DisposeReadingStates(reading);
            info?.Reading?.Dispose();
        }

        private static void DisposeReadingStates(IDeviceMessageInfoReading? reading)
        {
            if (reading?.State?.StateArray == null) return;
            foreach (var state in reading.State.StateArray) state?.Dispose();
        }

        ~DeviceMessage()
        {
            Dispose();
        }
    }
}
